import SelectTree from '../../../components/SelectTree.vue';
export default {
	name: 'user',
	components: {
		SelectTree
	},
	mounted: function() {
		//保存下初始值
		this.defaultData = JSON.parse(JSON.stringify(this.addForm));
		this.getParentId();
		this.currentUser = !localStorage.getItem("userInfo") ? {} : JSON.parse(localStorage.getItem("userInfo"));
		if (!this.currentUser) {
			this.$router.push({
				path: '/login'
			})
		}
		this.findCompanyList();
		this.findUserName();
	},
	methods: {
		//查询按钮执行方法
		queryPage: function() {
			this.query(1);
			//this.queryGroup();
			this.queryCompany();
		},
		//查询
		query: function(pageNum) {
			this.loading = true;
			let params = {
				companyId: this.currentUser.companyId
			};
			let url = '/api/users?pageIndex=' + pageNum + '&pageSize=' + this.pageInfo.pageSize;
			this.axios.hPost(url, params, (response) => {
				this.loading = false;
				if (!response.success) {
					this.$message.error(response.msg);
				}

				if (!response.data) {
					return;
				}
				this.itemList = response.data.list;
				this.pageInfo.totalNum = response.data.totalCount;
			});
		},
		//分页size变化
		handleSizeChange(val) {
			this.pageInfo.pageSize = val;
			this.query(1);
		},
		//翻页
		handleCurrentChange(val) {
			this.query(parseInt(val));
		},
		//加载分组
		queryGroup() {
			this.axios.hPost("/api/group/querys", {}, (response) => {
				if (!response.success) {
					this.$message.error(response.msg);
				}
				this.groupList = response.data;
			});
		},
		//加载单位名称
		queryCompany() {
			this.axios.hPost("/api/company/querys", {}, (response) => {
				if (!response.success) {
					this.$message.error(response.msg);
				}
				this.companyIdList = response.data;
				console.log(this.companyIdList);
				if (response.data.length === 1) {
					this.subCompanyIdList = response.data[0].children;
				} else {
					this.subCompanyIdList = [1, 2]
				}
				console.log(this.subCompanyIdList.length);
				console.log(this.subCompanyIdList);
				if (!this.companyIdList) {
					this.companyIdList = [];
				}
			});
		},
		//显示增加窗口()
		showAddDialog() {
			this.formTitle = this.$t('user.newUser');
			this.saving = false;
			if (this.$refs['addForm']) {
				this.$refs['addForm'].resetFields();
				this.addForm = Object.assign(this.addForm, this.defaultData);
			}
			this.addFormVisible = true;
		},
		showModifyDialog(row) {
			this.formTitle = this.$t('user.modifyUser');
			this.saving = false;
			this.addFormVisible = true;
			if (this.$refs['addForm']) {
				this.$refs['addForm'].resetFields();
			}
			this.addForm.id = row.id;
			this.addForm.user_name = row.user_name;
			this.addForm.real_name = row.real_name;
			this.addForm.company_id = row.company_id + "";
			this.addForm.phone = row.mobilephone_number;
			this.addForm.expire_time = row.expire_time;
			//this.addForm.password = '123';//随便设置的值 防止验证
		},
		//保存或修改用户
		saveOrUpdateUser() {
			this.saving = true;
			let url = '/api/users/insert';
			if (!!this.addForm.id) {
				url = '/api/users/update';
			}
			this.$refs['addForm'].validate((valid) => {
				if (valid) {
					let params = {
						id: this.addForm.id,
						userName: this.addForm.user_name,
						realName: this.addForm.real_name,
						companyId: this.addForm.company_id,
						password: this.$getMD5(this.addForm.password),
						mobilephoneNumber: this.addForm.phone,
						expireTime: this.addForm.expire_time,
						email: this.addForm.user_name,
					};
					this.axios.hPost(url, params, (response) => {
						if (response.success) {
							this.$message.success(response.msg);
							this.addFormVisible = false;
							this.query(1);
						} else {
							this.$message.error(response.msg);
						}
						this.saving = false;
					});
				} else {
					this.saving = false;
					return false;
				}
			});
		},
		//删除用户
		deleteUser(id) {
			this.$confirm(this.$t('message.DDUser'), this.$t('standard.prompt'), {
				confirmButtonText: this.$t('standard.confirm'),
				cancelButtonText: this.$t('standard.cancel'),
				type: 'warning'
			}).then(() => {
				this.axios.hPost('/api/users/delete', {
					id: id
				}, (response) => {
					if (response.success) {
						this.$message.success(response.msg);
						this.addFormVisible = false;
						this.query(1);
					} else {
						this.$message.error(response.msg);
					}
				});
			});
		},
		//显示配置权限窗口
		showConfigAuth(row) {
			this.currentId = row.id;
			this.axios.hPost('/api/menu/queryMenusInTree', {
				group_id: row.group_id
			}, (response) => {
				if (response.success) {
					this.menuList = response.data;
					this.configVisible = true;
					this.userMenus = [];
					for (let a of row.auths) {
						this.userMenus.push(a.id);
					}
					this.configLoading = false;
					this.configVisible = true;
					setTimeout(() => {
						this.$refs.tree.setCheckedKeys(this.userMenus);
					}, 200);
				} else {
					this.$message.error(response.msg);
				}
			});
		},
		configAuth() {
			//被选中的菜单ID 只包含二级
			let selectMenuId = this.$refs.tree.getCheckedKeys(true);
			let menuIds = '';
			for (let mid of selectMenuId) {
				menuIds += mid + ',';
			}
			this.$confirm(this.$t('message.DDMenus'), this.$t('standard.prompt'), {
				confirmButtonText: this.$t('standard.confirm'),
				cancelButtonText: this.$t('standard.cancel'),
				type: 'warning'
			}).then(() => {
				this.axios.hPost('/api/auth/saveAuths', {
					menuIds: menuIds,
					userId: this.currentId
				}, (response) => {
					if (response.success) {
						this.$message.success(response.msg);
						this.configVisible = false;
						this.query(1);
					} else {
						this.$message.error(response.msg);
					}
				});
			});
		},
		//树形控件重置
		cleanSelected() {
			this.$refs.tree.setCheckedKeys([]);
		},

		findCompanyList: function() {
			this.axios.hGet('/api/company/findAll', {}, (response) => {
				this.companyList = response;
				this.queryPage(1);
			});
		},

		getCompanyName: function(companyId, companyName) {
			if (!companyId) {
				return '';
			}

			if (!this.companyList) {
				return '';
			}

			companyName = "";
			while (companyId != 0) {
				var index = true;
				this.companyList.find(item => {
					if (item.id == companyId) {
						if (!companyName) {
							companyName = item.companyName;
						} else {
							companyName = item.companyName + " - " + companyName;
						}

						companyId = item.parentId;
						index = false;
						return false;
					}
				});

				if (index) {
					return companyName;
				}
			}
			this.fullText = companyName;
			return companyName;
		},
		getParentId() {
			this.axios.hPost('/api/company/getParentId', {}, (response) => {
				let companyParentId = response.parentId;
				console.log(response)
				this.companyParentId = companyParentId;
				this.addForm.company_id = response.id;
				this.companyName = response.companyName;
				if (response.id !== -99) {
					this.adminName = response.contact;
					console.log('adminName' + this.adminName);
				} else {
					this.adminName = "超级管理员";
				};
			});
		},
		findUserName() {
			this.axios.hPost('/api/device/getRealName', {}, (response) => {
				this.realAdminName = response;
				console.log('realAdminName' + this.realAdminName);
			})
		}
	},
	data() {
		return {
			//存放搜索框数据
			searchForm: {
				name: '',
				type: '-1',
				source: '-1'
			},
			companyName: null,
			adminName: null,
			//存放列表数据
			itemList: [],
			//存放分页数据
			pageInfo: {
				currentPage: 1,
				pageSize: 10,
				totalNum: 0
			},
			//分组数据
			groupList: [],
			//单位数据
			companyIdList: [],
			subCompanyIdList: [],
			companyList: [],
			//是否在加载标记
			loading: true,
			saving: false,
			addFormVisible: false,
			importVisible: false,
			addForm: {
				id: null,
				user_name: '',
				real_name: '',
				password: '',
				company_id: '',
				phone: '',
				expire_time: new Date(),
			},
			formTitle: this.$t('user.newUser'),
			addRules: {
				user_name: [{
						required: true,
						message: this.$t('message.required'),
						trigger: 'blur'
					},
					{
						max: 50,
						message: this.$t('message.length50'),
						trigger: 'blur'
					},
					{
						type: 'email',
						message: this.$t('login.inputEmail'),
						trigger: 'blur'
					}
				],
				real_name: [{
						required: true,
						message: this.$t('message.required'),
						trigger: 'blur'
					},
					{
						max: 50,
						message: this.$t('message.length50'),
						trigger: 'blur'
					},
					{
						pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/,
						message: this.$t('message.incorrectFormat'),
						trigger: 'blur'
					}
				],
				password: [{
						required: true,
						message: this.$t('message.required'),
						trigger: 'blur'
					},
					{
						max: 50,
						message: this.$t('message.length50'),
						trigger: 'blur'
					},
					{
						pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/,
						message: this.$t('message.incorrectFormat'),
						trigger: 'blur'
					}
				],
				// company_id: [
				//     {required: true, message: '本字段必选', trigger: 'change'},
				// ],
				phone: [{
						required: true,
						message: this.$t('message.inputPhone'),
						trigger: 'blur'
					},
					{
						max: 20,
						message: this.$t('message.length20'),
						trigger: 'blur'
					},
					{
						pattern: /(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}/,
						message: this.$t('message.incorrectFormat'),
						trigger: 'blur'
					}
				],
				expire_time: [{
					required: true,
					message: this.$t('message.required'),
					trigger: 'blur'
				}, ]
			},

			configVisible: false,
			configLoading: false,
			menuList: [],
			// defaultProps: {
			//     children: 'chlidList',
			//     label: 'menuName'
			// },
			currentId: null,
			userMenus: [],
			// 数据默认字段
			defaultProps: {
				parent: 'parentId', // 父级唯一标识
				value: 'id', // 唯一标识
				label: 'text', // 标签显示
				children: 'children', // 子级
			},
			currentUser: {},
			fullText: null,
			companyParentId: null,
			realAdminName: null,
		}
	}
}
